package edu.gdut.tiantian.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;

import edu.gdut.tiantian.entity.User;
import edu.gdut.tiantian.service.Impl.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/findAll.do")
	public ModelAndView findByCondition(Integer pageNum, HttpServletRequest req) {
		Map<String, String> condition = new HashMap<>();
		Enumeration<String> paramNames = req.getParameterNames();
		StringBuffer conditionStr = new StringBuffer();
		while(paramNames.hasMoreElements()) {
			String key = paramNames.nextElement();
			String value = req.getParameter(key);
			if(value != null && value.trim().length() !=0) {
				condition.put(key, value);
				conditionStr.append("&"+key+"="+value);
			}
		}
		ModelAndView mv = new ModelAndView();
		List<User> userList = userService.findByCondition(condition,pageNum);
		PageInfo<User> pageInfo = new PageInfo<User>(userList);
		mv.addObject("condition",conditionStr);
		mv.addObject("pageInfo",pageInfo);
		mv.setViewName("background/user-manager");
		return mv; 
	} 
	
	@RequestMapping("/updateStatus")
	public String updateStatus(String userId,Integer status) {
		userService.updateStatus(userId,status);
		return "redirect:/user/findAll.do?pageNum=0";
	}
	
	@RequestMapping("/login.do")
	public ModelAndView login(String username,String password,HttpServletRequest req) {
		ModelAndView mv = new ModelAndView();
		User user = userService.userLogin(username, password);
		if(user==null) {
			mv.addObject("msg","用户名或密码错误,请重试!");
			mv.setViewName("user/login");
		}else {
			req.getSession().setAttribute("user", user);
			mv.setViewName("user/index");
		}
		return mv;
	}
	
	@RequestMapping("/logout.do")
	public String loginout(HttpServletRequest req) {
		req.getSession().invalidate();
		return "forward:/pages/user/login.jsp";
	}
	
	@RequestMapping("/updateUser.do")
	public String updateUser(User user,HttpServletRequest req) {
		User oldUser = (User)req.getSession().getAttribute("user");
		user.setId(oldUser.getId());
		userService.updateUser(user);
		req.getSession().setAttribute("user", user);
		return "forward:/pages/user/index.jsp";
	}
	
	@RequestMapping("/register.do")
	public String register(User user) {
		userService.save(user);
		return "forward:/pages/user/login.jsp";
	}
	
}
